﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla.Rules;
using System.Text.RegularExpressions;

namespace Validation
{
    public class EmailValidation : ValidationBase
    {
        public string pattern { get; set; }
        public EmailValidation(Csla.Core.IPropertyInfo PrimaryProperty, string ValidationMessage)
            : base(PrimaryProperty, ValidationMessage)
        {
            this.pattern = @"^[a-z][a-z|0-9|]*([_][a-z|0-9]+)*([.][a-z|" +
               @"0-9]+([_][a-z|0-9]+)*)?@[a-z][a-z|0-9|]*\.([a-z]" +
               @"[a-z|0-9]*(\.[a-z][a-z|0-9]*)?)$";

           // this.pattern = @"^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\.(com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|tv|[a-zA-Z]{2})$";
            InputProperties = new List<Csla.Core.IPropertyInfo> { PrimaryProperty };
        }

        protected override void Execute(RuleContext context)
        {
            string primaryValue = (string)context.InputPropertyValues[PrimaryProperty];
            if (primaryValue != "")
            {

                System.Text.RegularExpressions.Match match = Regex.Match(primaryValue, pattern, RegexOptions.IgnoreCase);
                if (!match.Success)
                {
                    context.AddErrorResult(this.ValidationMessage);
                    return;
                }
            }
        }
    }
}
